package com.day.newcorp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ValidityToken {

	List<Field> fields;

	public ValidityToken() {
		fields = new ArrayList<Field>();
	}

	public ValidityToken(String tokenString) throws Exception {
		if (Integer.parseInt(tokenString.substring(0, 3)) != tokenString
				.substring(3).length())
			throw new Exception("invalid token");

		fields = new ArrayList<Field>();
		String tkn = tokenString.substring(3);
		while (tkn.length() != 0) {
			int length = Integer.parseInt(tkn.substring(0, 2));
			fields.add(new Field(Integer.parseInt(tkn.substring(2, 4)), tkn
					.substring(4, length + 2)));
			tkn = tkn.substring(2 + length);
		}
	}

	public void addField(Field field) {
		boolean available = false;
		for (Field f : fields)
			if (field.getPosition() == f.getPosition())
				available = true;
		if (!available)
			fields.add(field);
	}

	public String getTokenString() {
		StringBuffer sb = new StringBuffer();
		for (Field f : fields)
			sb.append(f);
		return new DecimalFormat("000").format(sb.length()) + sb.toString();
	}

	public List<Field> getFields() {
		return fields;
	}
}
